using System;
using System.Web;
using Impact.Controllers;
using Impact.Model.Objects;

namespace Impact.Web.Foundation
{
    /// <summary>
    /// Sitemap provider for Impact
    /// </summary>
    public class ImpactSiteMapProvider : StaticSiteMapProvider
    {
        private SiteMapNode root;

        /// <summary>
        /// Creates the sitemap for the current state of the application
        /// </summary>
        /// <returns></returns>
        public override SiteMapNode BuildSiteMap()
        {
            if ( root == null )
            {
                lock ( this )
                {

                    root = new SiteMapNode( this, "Menu" );

                    ImpactPageCollection pages = MenuController.GetTopLevelPages();

                    foreach ( ImpactPage page in pages )
                    {
                        SiteMapNode node = CreateNode( page );
                        AddNode( node, root );
                    }

                }
            }

            return root;
        }

        private SiteMapNode CreateNode( ImpactPage page )
        {
            SiteMapNode node = new SiteMapNode( this, page.PageKey,
                ContentPresenter.FormatUrl( page ), page.Title );
            foreach ( ImpactPage childPage in page.ChildPages )
            {
                SiteMapNode childNode = CreateNode( childPage );
                AddNode( childNode, node );
            }
            return node;
        }

        /// <summary>
        /// Retrieves the overall sitemap
        /// </summary>
        /// <returns></returns>
        protected override SiteMapNode GetRootNodeCore()
        {
            return BuildSiteMap();
        }



    }
}
